<?php

namespace App\Http\Controllers;

use App\Configuration;
use App\Property;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use App\Client;


class ClientController extends Controller
{
    public function __construct () {
        $this->middleware('auth');
    }

    public function myClients() {
        $clients = Auth::user()->clients->where('is_finished','=',0);
        $dealers = Auth::user()->clients->where('is_finished','>',0);
        return view('client.myClients',compact('clients','dealers'));
    }


    public function edit(Client $client) {
        return view('client.edit',compact('client'));
    }

    public function index() {
        $clients = Client::all();
        return view('client.index',compact('clients'));
    }

    public function create() {
        $properties = Property::all();
        $propertieTypes = Configuration::whereKey('property_type')->first()->value;
        $propertyTypes = explode(',',$propertieTypes);
        return view('client.create',compact('properties','propertyTypes'));
    }

    public function store (Request $request) {


        $this->validate($request, [
            'name'=>'required|max:40',
            'phone' => 'required|digits:11',
        ]);

        $data = $request->all();
        $data['user_id'] = Auth::user()->id;

        $client = Client::wherePhone($request->input('phone'))->first();
        if ($client) {
            $client->update($data);
        } else {
            Client::create($data);
        }

        return response()->json('添加成功');
    }

    public function update(Request $request,Client $client) {
        $this->validate($request, [
            'name'=>'required|max:40',
            'phone' => 'required|digits:11',
        ]);

        $data = $request->all();
//        dd($data);
        $client->update($data);
        return redirect(route('client.index'));
    }

    public function destroy(Client $client){
        $client->delete();
        return redirect(route('client.index'));
    }

    public function show(Client $client) {
        return view('client.show',compact('client'));
    }



}
